package ru.electron.menu.fragments;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import ru.electron.menu.R;
import ru.electron.menu.provider.MenuProvider;

import javax.xml.soap.Text;
import java.io.IOException;

public class DishDetailsFragment extends Fragment {


    private ImageView image;
    private int countOrder;
    private TextView countTextView;


    private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... strings) {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(strings[0]);
                try {

                    HttpResponse resp = client.execute(get);
                    final Bitmap bitmap = BitmapFactory.decodeStream(resp.getEntity().getContent());
                    return bitmap;

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap == null) {
                return;
            }
            image.setImageBitmap(bitmap);
            image.invalidate();
        }
    }


    private static final String DISH_ID = "dish";

    private static final String IS_GONE = "gone";

    public static DishDetailsFragment newInstance(int index, boolean gone) {
        DishDetailsFragment fragment = new DishDetailsFragment();
        Bundle b = new Bundle();
        b.putInt(DISH_ID, index);
        b.putBoolean(IS_GONE, gone);
        fragment.setArguments(b);
        return fragment;
    }

    public int getDishID() {
        Bundle args = getArguments();
        if (args == null) {
            return -1;
        }
        return args.getInt(DISH_ID, -1);
    }


    public boolean isGone() {
        Bundle args = getArguments();
        if (args == null) {
            return false;
        }
        return args.getBoolean(IS_GONE, false);
    }

    private static void setTextValue(Cursor c, String columnName, View parent, int id) {
        TextView text = (TextView) parent.findViewById(id);
        int index = c.getColumnIndex(columnName);
        text.setText(c.getString(index));
    }


    private void changeOrderCounter(int change) {
        countOrder += change;
        ContentValues values = new ContentValues();
        values.put(MenuProvider.KEY_COUNT, countOrder);
        countTextView.setText(countOrder + "");
        countTextView.invalidate();

        Uri updateUri = Uri.withAppendedPath(MenuProvider.URI_ORDER, getDishID() + "");
        getActivity().getContentResolver().update(updateUri, values, null, null);
    }

    private Cursor cursor;

    private void initCounter() {
        if (!isGone()) {
            countOrder = cursor.getInt(cursor.getColumnIndex(MenuProvider.KEY_COUNT));
        }else {
            countOrder = cursor.getInt(cursor.getColumnIndex(MenuProvider.KEY_ORDERED));
        }
        countTextView.setText("" + countOrder);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (cursor == null) {
            return;
        }
        cursor.requery();
        cursor.moveToFirst();
        initCounter();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (container == null) {
            return inflater.inflate(R.layout.greeting, container, false);
        }
        container.removeAllViews();

        int dishId = getDishID();
        if (dishId == -1) {
            return inflater.inflate(R.layout.greeting, container, false);
        }


        cursor = getActivity().managedQuery(Uri.withAppendedPath(MenuProvider.URI_DISHES, "" + dishId), null, null, null, null);
        if (!cursor.moveToFirst()) {
            return inflater.inflate(R.layout.greeting, container, false);
        }

        View v = inflater.inflate(R.layout.dish, container, false);
        image = (ImageView) v.findViewById(R.id.image);
        setTextValue(cursor, MenuProvider.KEY_DISH_NAME, v, R.id.title);
        setTextValue(cursor, MenuProvider.KEY_DESCRIPTION, v, R.id.description);
        setTextValue(cursor, MenuProvider.KEY_PRICE, v, R.id.price);
        DownloadImage image = new DownloadImage();
        image.execute(cursor.getString(cursor.getColumnIndex(MenuProvider.KEY_URI)));

        countTextView = (TextView) v.findViewById(R.id.count);
        initCounter();
        final Button plus = (Button) v.findViewById(R.id.plus);
        final Button minus = (Button) v.findViewById(R.id.minus);
        if (isGone()) {
            plus.setVisibility(View.GONE);
            minus.setVisibility(View.GONE);
        }
        minus.setEnabled(countOrder > 0);
        plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeOrderCounter(1);
                minus.setEnabled(true);
            }
        });

        minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeOrderCounter(-1);
                if (countOrder == 0) {
                    minus.setEnabled(false);
                }
            }
        });


        return v;
    }
}
